import {
  valueAddedGet,
  queryProductLineList,
  queryOriginalFactoryList,
  valueAddedAdd,
  valueAddedUpdate,
  updateBatch,
  saveOrderType
} from '@api/system_config_v1.js';
export default {
  data() {
    return {
      params: {
        isMust: 1
      },
      originalFactoryList: [],
      productLineList: [],
      originalFactoryMap: {},
      productLineMap: {},
      checkList: [],
      selectList: [],
      orderTypeList: [],
      loading: false,
      switchValue: false,
      attributeType: 1,
      orderTypeInfo: [],
      optionList: [],
      defaultOption: {label: '', value: ''}
    }
  },
  created() {
    this.initData()
    this.initGlobalBtn()
    // this.setCheckBoxList()
    this.defaultValueLabel = ''
    this.infoId = this.$route.query.id
    this.appendFieldId = this.$route.query.appendFieldId
    this.infoId && this.getInfo()
  },
  methods: {
    initData () {
      // 1-input；3-select；4-date; 5-number; 6-date-time
      // 批发-普通订单、批发-换货、批发-退货、长期寄售订单、长期寄售确认销货单、长期寄售-退货、长期寄售-换货、短期寄售订单
      this.orderTypeList = [
        {label: '普通订单', value: 'WHOLESALE_ISSUE'},
        {label: '促销订单', value: 'WHOLESALE_PROM'},
        {label: '返利订单', value: 'WHOLESALE_REBATE'},
        {label: '批发-换货', value: 'WHOLESALE_ISSUE'},
        {label: '批发-退货', value: 'WHOLESALE_RETURN'},
        {label: '长期寄售', value: 'LCONSIGN_INIT'},
        {label: '长期寄售确认销货单', value: 'LCONSIGN_ISSUE'},
        {label: '长期寄售-退货', value: 'LCONSIGN_TRANSFER'},
        {label: '长期寄售-换货', value: 'LCONSIGN_INIT'},
        {label: '短期寄售', value: 'SCONSIGN_LENG'}
      ]
      this.valueTypeList = [
        {label: '文本输入框', value: 1},
        {label: '下拉选项框', value: 3},
        {label: '日期控件', value: 4},
        {label: '数字输入框', value: 5},
        {label: '时间控件', value: 6}
      ]
      this.initOptionData()
    },
    initOptionData () {
      this.defaultOption = {label: '', value: ''}
      this.optionList = [
        {label: '', value: ''}
      ]
    },
    addOption () {
      this.optionList.push({label: '', value: ''})
    },
    delOption (v) {
      const index = this.optionList.findIndex(o => o.label === v)
      this.optionList.splice(index, 1)
    },
    onTypeChange (v) {
      if (v !== 3) {
        this.initOptionData()
      }
    },
    getInfo () {
      this.initGlobalBtn()
      const url = valueAddedGet + '/' + this.infoId
      this.$axios.$get(url).then(({payload}) => {
        let obj = {}
        obj.attributeName = payload.attributeName
        obj.attributeType = payload.attributeType
        obj.orderTypeName = payload.orderTypeName
        obj.isMust = payload.isMust
        obj.productLineCode = [payload.productLineCode]
        obj.originalFactoryCode = payload.vendorNum
        this.params = obj
        this.defaultOption = {value: payload.defaultValue, label: ''}
        if (payload.valueRangeList && payload.valueRangeList.length) {
          this.optionList = []
          payload.valueRangeList.forEach(item => {
            if (item.value === this.defaultOption.value) {
              this.defaultOption.label = item.label
              this.defaultValueLabel = item.label
            } else {
              this.optionList.push(
                {label: item.label, value: item.value}
              )
            }
          })
          if (!this.optionList.length) {
            this.optionList = [
              {label: '', value: ''}
            ]
          }
        }
        this.originalFactoryMap = {
          [payload.vendorNum]: payload.vendorName
        }
        this.productLineMap = {
          [payload.productLineCode]: payload.productLineName
        }
        this.originalFactoryList = [
          {originalFactoryName: payload.vendorName, originalFactoryCode: payload.vendorNum}
        ]
        this.productLineList = [
          {productLineName: payload.productLineName, productLineCode: payload.productLineCode}
        ]
      })
    },
    initGlobalBtn() {
      let btnObj = {
        type: 'btn',
        arr: []
      };
      let submitBtn = {
        type: 'primary',
        val: this.infoId ? '修改' : '提交',
        handle: this.onSubmit
      };
      btnObj.arr.push(submitBtn);
      this.$store.commit('changeLayoutHandle', btnObj);
    },
    onSubmit () {
      const rules = [
        'originalFactoryCode',
        'orderTypeName', 'attributeName',
        'attributeType'
      ]
      const rulesMap = {
        'originalFactoryCode': '请选择原厂',
        'orderTypeName': '请选择订单类型',
        'attributeName': '请输入附加值名称', 'attributeType': '请选择附加值类型'
      }
      let next = true
      let msg = ''
      rules.forEach(r => {
        if (!this.params[r]) {
          if (next) {
            next = false
            msg = rulesMap[r]
          }
        }
      })
      // valueRange
      let sendData = []
      let optValueList = []
      if (!this.params.productLineCode.length && next) {
        next = false
        msg = '请选择产品线 '
      }
      if (this.params.attributeType === 3) {
        if (!this.defaultOption.label && (this.optionList.length === 1 && !this.optionList[0].label)) {
          if (next) {
            next = false
            msg = '请输入默认值或至少一个选项'
          }
        }
        let optionArr = [...this.optionList]
        // 如果有默认值，加发送列表里
        if (this.defaultOption.label) {
          if (this.defaultOption.value && this.defaultValueLabel !== this.defaultOption.label) {
            delete this.defaultOption.value
          }
          optionArr.unshift(this.defaultOption)
        }
        let optLab = []
        optionArr.forEach(item => {
          if (this.optionList.length > 1 && !item.label) {
            if (next) {
              next = false
              msg = '附加值选项不能为空'
            }
          } else {
            const label = item.label.trim()
            if (label) {
              if (optLab.indexOf(label) > -1) {
                if (next) {
                  next = false
                  msg = '请勿输入重复的附加值选项'
                }
              } else {
                optLab.push(label)
                let obj = {label: label}
                // 如果没有value，不要添加
                item.value && (obj.value = item.value)
                optValueList.push(obj)
              }
            }
          }
        })
      }
      if (!next) return this.$message.warning(msg)
      this.params.productLineCode.forEach(item => {
        let obj = {
          attributeName: this.params.attributeName.trim(),
          attributeType: this.params.attributeType,
          isMust: this.params.isMust,
          productLineCode: item,
          ddbm: this.orderTypeList.filter(item => item.label === this.params.orderTypeName)[0].value,
          orderTypeName: this.params.orderTypeName,
          productLineName: this.productLineMap[item],
          vendorName: this.originalFactoryMap[this.params.originalFactoryCode],
          vendorNum: this.params.originalFactoryCode
        }
        if (this.params.attributeType === 3) {
          obj.valueRangeList = optValueList
          if (this.defaultOption.label) {
            obj.defaultValueName = this.defaultOption.label.trim()
            if (this.defaultOption.value && this.defaultValueLabel === this.defaultOption.label) {
              obj.defaultValue = this.defaultOption.value
            }
          }
        }
        sendData.push(obj)
      })
      let ex = valueAddedAdd
      let sendMsg = '添加成功'
      if (this.infoId) {
        sendData = sendData[0]
        sendData.id = this.infoId
        sendData.appendFieldId = this.appendFieldId
        ex = valueAddedUpdate
        sendMsg = '修改成功'
      }
      this.$axios.$post(ex, sendData).then(res => {
        this.$message.success(sendMsg)
        this.$router.go(-1)
      });
    },
    // 原厂下拉
    queryOriginalFactoryList(val) {
      if (val !== '') {
        this.loading = true;
        let query = {
          originalFactoryName: val,
        };
        this.$axios.$post(queryOriginalFactoryList, query).then(res => {
          this.setOriginList(res.payload, 'originalFactoryList', 'originalFactoryMap')
          this.loading = false;
        });
      }
    },
    // 产品线下拉
    queryProductLineList (val) {
      this.params.productLineCode = []
      this.loading = true;
      let query = {
        originalFactoryCode: this.params.originalFactoryCode,
        productLineName: val
      };
      this.$axios.$post(queryProductLineList, query).then(res => {
        this.productLineList = res.payload
        res.payload.forEach(item => {
          this.productLineMap[item.productLineCode] = item.productLineName
        })
        this.loading = false;
      });
    },
    setOriginList (data, key, mapKey) {
      this[key] = data
      data.forEach(item => {
        this[mapKey][item.originalFactoryCode] = item.originalFactoryName
      })
    }
  }
};
